/*
 *  example.cpp
 */

#include "MGame.h"

#include "MGame.h"
#include "tests.h"

using namespace std;

MGame::MGame()
{
}

Example::~MGame()
{
}

void MGame::Init()
{
	//initalize SDL
	if ( SDL_Init(SDL_INIT_VIDEO) != 0 )
	{
		cout << "Unable to initialize SDL: " << SDL_GetError() << endl;
		exit(1);
	}
	
	//setup window and surface flags
	m_Width = 800;
	m_Height = 600;
	m_Bpp = 32;
	m_WindowName = "An example cApp";
	m_SdlFlags = SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_HWPALETTE;
	m_FullScreen = false;
	
	const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo();
	
	if (videoInfo->hw_available)
		m_SdlFlags |= SDL_HWSURFACE;
	else
		m_SdlFlags |= SDL_SWSURFACE;
	
	atexit(SDL_Quit);
	
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, m_Bpp);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	
	//create the surface
	m_Surface = SDL_SetVideoMode(m_Width, m_Height, m_Bpp, m_SdlFlags);
	
	if ( m_Surface == NULL)
	{
		cout << "Video mode set failed: " << SDL_GetError() << endl;
		SDL_Quit();
	}
	
	//setup opengl
	glViewport(0, 0, (GLsizei)m_Width, (GLsizei) m_Height);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	InitGl();
	
	//set the window title
	SDL_WM_SetCaption(m_WindowName.c_str(), NULL);
}

void MGame::ResizeWindow(int width, int height)
{
	//resize sdl surface
	m_Surface = SDL_SetVideoMode( width, height, m_Bpp, m_SdlFlags );
	
	if (m_Surface == NULL)
	{
		cout << "Could not get a surface after resize: " << SDL_GetError() << endl;
		exit(1);
	}
	
	//change the view port
	glViewport(0, 0, ( GLsizei )width, ( GLsizei )height);
	
	//update the width/height
	m_Width = width;
	m_Height = height;
	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void MGame::InitGl()
{
	glShadeModel( GL_SMOOTH );
	glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
	glClearDepth( 0.0f );
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable( GL_DEPTH_TEST );
	glDepthFunc( GL_ALWAYS );
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
	
	glDisable(GL_LIGHTING);
}

void MGame::Run()
{
	//do main game stuff here
	
	TestProcess();
	TestStates();
	
	SDL_Delay(2000);
}

void MGame::Shutdown()
{
	exit(0);
}

void MGame::ToggleFullscreen()
{
	m_FullScreen = !m_FullScreen;
	
	SDL_WM_ToggleFullScreen(m_Surface);
	
	if (!m_FullScreen)
	{
		SDL_ShowCursor(SDL_ENABLE);
	}
	else
	{
		SDL_ShowCursor(SDL_DISABLE);
	}
}